package Pet.Management.controller;

import Pet.Management.domain.entity.PetDemand;
import Pet.Management.service.PetDemandService;
import Pet.Management.service.MessageService;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/pet/demand")
@RequiredArgsConstructor
@CrossOrigin
public class PetDemandController {

    private final PetDemandService petDemandService;
    private final MessageService messageService;
    private final UserRepository userRepository;

    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String petType) {
        
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        Page<PetDemand> page = petDemandService.getAllPetDemands(pageRequest);
        
        Map<String, Object> response = new HashMap<>();
        response.put("total", page.getTotalElements());
        response.put("rows", page.getContent());
        response.put("code", 200);
        response.put("msg", "查询成功");
        
        return ResponseEntity.ok(response);
    }

    @PostMapping
    public ResponseEntity<PetDemand> createPetDemand(@RequestBody PetDemand petDemand) {
        return ResponseEntity.ok(petDemandService.createPetDemand(petDemand));
    }

    @PutMapping("/{id}")
    public ResponseEntity<PetDemand> updatePetDemand(@PathVariable Long id, @RequestBody PetDemand petDemand) {
        return ResponseEntity.ok(petDemandService.updatePetDemand(id, petDemand));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePetDemand(@PathVariable Long id) {
        petDemandService.deletePetDemand(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<PetDemand> getPetDemand(@PathVariable Long id) {
        return ResponseEntity.ok(petDemandService.getPetDemand(id));
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<PetDemand>> getPetDemandsByUserId(@PathVariable Long userId) {
        return ResponseEntity.ok(petDemandService.getPetDemandsByUserId(userId));
    }

    @GetMapping("/search")
    public ResponseEntity<List<PetDemand>> searchPetDemands(
            @RequestParam(required = false) String petName,
            @RequestParam(required = false) String petType,
            @RequestParam(required = false) String petGender) {
        return ResponseEntity.ok(petDemandService.searchPetDemands(petName, petType, petGender));
    }

    @PostMapping("/message")
    public ResponseEntity<?> sendPrivateMessage(@RequestBody Map<String, Object> payload) {
        try {
            // 检查必要参数
            if (!payload.containsKey("demandId") || payload.get("demandId") == null) {
                return ResponseEntity.badRequest().body("需求ID不能为空");
            }
            Long demandId = Long.valueOf(payload.get("demandId").toString());
            
            if (!payload.containsKey("message") || payload.get("message") == null) {
                return ResponseEntity.badRequest().body("消息内容不能为空");
            }
            String message = (String) payload.get("message");
            
            // 处理可选的senderId参数，如果不存在，使用默认值1L (系统用户)
            Long senderId = 1L; // 默认为系统用户ID
            if (payload.containsKey("senderId") && payload.get("senderId") != null) {
                senderId = Long.valueOf(payload.get("senderId").toString());
            }
    
            // 获取需求信息
            PetDemand demand = petDemandService.getPetDemand(demandId);
            if (demand == null) {
                return ResponseEntity.badRequest().body("需求不存在");
            }
    
            // 发送私信
            messageService.sendPrivateMessage(
                senderId,
                demand.getUserId(),
                "宠物需求咨询",
                message
            );
    
            return ResponseEntity.ok().body("消息发送成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("发送失败: " + e.getMessage());
        }
    }
} 